/**
 * modal 图标
 * @param {string|number} icon
 * @return {*}
 */
const MODAL_ICONS = {
	warn: 0,
	success: 1,
	error: 2,
	question: 3,
	unauthorized: 4,
};

/**
 * modal
 * @param {{
 * title?:string,
 * content?:string,
 * confirmText?:string,
 * cancelText?:string,
 * showCancel?:boolean,
 * icon?:string,
 * area?:Array,
 * thisArg?:*,
 * created?:Function,
 * closed?:Function,
 * }|*} options
 * @return Promise<*>
 */
export default function(options) {
	if (typeof options === 'string') {
		options = {
			title: false,
			content: options,
			showCancel: false
		};
	} else {
		options = Object.assign({
			title: false,
			showCancel: false
		}, options);
	}

	if (options.icon) {
		options.icon = MODAL_ICONS[options.icon];
	}

	if (options.showCancel && options.icon === undefined) {
		options.icon = MODAL_ICONS.question;
	}

	// 转换与剔除不必要的字段
	options.success = options.created;
	delete options.created;

	// btn text
	if (options.btn !== false) {
		options.btn = [];
		options.btn.push(options.confirmText || '确认');
		if (options.showCancel) {
			options.btn.push(options.cancelText || '取消');
		}
	}

	return new Promise((resolve) => {
		const triggerEvent = function(result) {
			resolve(result);
			if (result.id) {
				layer.close(result.id);
			}
		};

		options.end = function() {
			resolve({
				confirm: false,
				cancel: true,
				close: true
			});
		};

		options.yes = function(id) {
			triggerEvent({
				id: id,
				confirm: true,
				cancel: false,
			});
		};

		options.btn2 = function(id) {
			triggerEvent({
				id: id,
				confirm: false,
				cancel: true,
			});
		};

		layer.open(options);
	});
};
